package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService ;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户
        User user = userService.findByUsername(username); // 用户信息  用户角色信息  角色的权限信息
        if(user==null){
            return null;
        }
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        Set<Role> roles = user.getRoles();
        roles.forEach(role -> {
                // 框架在接收到认证信息的时候 如何区分是 角色 还是 权限呢 ?
                // 如果是以ROLE_开头的 , 就认为是角色 , 否则是权限

                //添加认证信息
                authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
                //获取权限信息
                Set<Permission> permissions = role.getPermissions();
                permissions.forEach(permission -> authorities.add(new SimpleGrantedAuthority(permission.getKeyword())));
        });

        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
    }
}
